package com.zyk.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangsan
 * @date 2021/4/29 9:08
 */
public class C403 {

    public static boolean canCross(int[] stones) {
        return process(stones, 0, 0);
    }

    public static boolean process(int[] stones, int i, int pre) {
        if (i == stones.length - 1) return true;
        for (int index = i + 1; index < stones.length; index++) {
            int difference = stones[index] - stones[i];
            if (difference > pre + 1) break;
            if (difference < pre - 1) continue;
            boolean after = process(stones, index, difference);
//            System.out.print("当前位置: " + i + ", 想跳跃的位置: " + index + ", 是否可以跳跃成功: " + after);
//            System.out.print(", 上一步跳跃的距离:" + pre + ", 当前的差值: " + difference);
//            System.out.println();
            if (after) return after;
        }
        return false;
    }

    // map记忆话搜索
    public static boolean canCross2(int[] stones) {
        Map<Integer, Map<Integer, Boolean>> dp = new HashMap<>();
        return process1(stones, 0, 0, dp);
    }

    public static boolean process1(int[] stones, int i, int pre, Map<Integer, Map<Integer, Boolean>> dp) {
        if (i == stones.length - 1) return true;

        if (dp.containsKey(i) && dp.get(i).containsKey(pre)) return dp.get(i).get(pre);
        boolean ans = false;

        for (int index = i + 1; index < stones.length; index++) {
            int difference = stones[index] - stones[i];
            if (difference > pre + 1) break;
            if (difference < pre - 1) continue;
            boolean after = process1(stones, index, difference, dp);
            if (after) {
                ans = true;
                break;
            }
        }

        if (!dp.containsKey(i)) dp.put(i, new HashMap<>());
        dp.get(i).put(pre, ans);
        return ans;
    }

    // 计划搜索, Boolean数组
    public static boolean canCross3(int[] stones) {
        Boolean[][] dp = new Boolean[stones.length][stones.length];
        return process3(stones, 0, 0, dp);
    }

    public static boolean process3(int[] stones, int i, int pre, Boolean[][] dp) {
        if (i == stones.length - 1) return true;
        if (dp[i][pre] != null) return dp[i][pre];
        boolean ans = false;
        for (int index = i + 1; index < stones.length; index++) {
            int difference = stones[index] - stones[i];
            if (difference > pre + 1) break;
            if (difference < pre - 1) continue;
            boolean after = process3(stones, index, difference, dp);
            if (after) {
                ans = true;
                break;
            }
        }
        dp[i][pre] = ans;
        return ans;
    }

    // for test
    public static void main(String[] args) {
        int[] stones = {0, 1, 3, 6, 10, 15};
        System.out.println(canCross(stones));
        System.out.println(canCross2(stones));
        System.out.println(canCross3(stones));
    }

}
